package com.ruoyi.framework.manager

import com.ruoyi.common.utils.Threads
import com.ruoyi.common.utils.spring.SpringUtils
import java.util.*
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

/**
 * 异步任务管理器
 *
 * @author ruoyi
 */
class AsyncManager
/**
 * 单例模式
 */
private constructor() {
    /**
     * 操作延迟10毫秒
     */
    private val OPERATE_DELAY_TIME = 10

    /**
     * 异步操作任务调度线程池
     */
    private val executor: ScheduledExecutorService =
        SpringUtils.getBean("scheduledExecutorService")

    /**
     * 执行任务
     *
     * @param task 任务
     */
    fun execute(task: TimerTask) {
        executor.schedule(task, OPERATE_DELAY_TIME.toLong(), TimeUnit.MILLISECONDS)
    }

    /**
     * 停止任务线程池
     */
    fun shutdown() {
        Threads.shutdownAndAwaitTermination(executor)
    }

    companion object {
        private val me: AsyncManager = AsyncManager()
        fun me(): AsyncManager {
            return me
        }
    }
}
